import SocketIO from 'socket.io-client'

const UTalkSDK = {
    accessKeyId: null,
    socket: null,
    isConnected: false,
    userInfo: null,
    listenHistoryMsgCallBack: null,
    listenRecentChatsCallBack: null,
    listenUserInfoCallBack: null,
    listenUserId: null,
    init: function (accessKeyId, userId, nickName, avatar, token) {
        const _this = this;
        _this.accessKeyId = accessKeyId;
        _this.userInfo = { userId, nickName, avatar }

        _this.socket = SocketIO.connect('ws://suj.cloud.api.uutils.com', {
            // reconnectionDelayMax: 30000,
            // reconnectionDelay: 5000,
            query: { token },
            transports: ["websocket"]
        });

        //监听本次连接回调函数
        _this.socket.on('connect', () => {
            console.log("连接成功");
            if (_this.isConnected) {
                _this.socket.disconnect();
            }
            _this.isConnected = true;
            //更新当前用户的信息
            _this.updateUserInfo(nickName, avatar)
            //向服务器请求离线消息
            _this.receiveOfflineMsg()

        });
        //监听断开
        _this.socket.on('disconnect', () => {
            console.error("连接断开");
            _this.isConnected = false;
        });
        //监听断开错误
        _this.socket.on('connect_error', (data) => {
            console.log(data);
        });
        //监听单聊消息
        _this.socket.on('single.chat.msg', (msgInfo) => {
            //如果当前监听的用户与发送消息用户一致，说明用户正在此聊天窗口，则将消息直接已读
            if (_this.listenUserId && _this.listenUserId === msgInfo.from.userId) {
                msgInfo = { ...msgInfo, isRead: 'Y' }

                _this.socket.emit("single.read.msg", {
                    toUserId: msgInfo.from.userId,
                    msgIds: [msgInfo.id]
                }, function (state) {
                    console.log("single.read.msg", state);
                });
            }
            //保存聊天对象到本地
            _this._setStorageUserInfo(msgInfo.from);
            //保存历史消息
            _this._setStorageHistoryMsg(msgInfo.from.userId, msgInfo);


        });
        //监听消息已读状态
        this.socket.on('single.read.msg', (data) => {
            //更新消息已读状态
            _this._setMsgReadSate(data)
        });

        return _this;
    },
    initSingleChat(toUserId, userInfoCallBack) {
        this.listenUserId = toUserId;
        this.listenUserInfoCallBack = userInfoCallBack;
        console.log('开始聊天', this.listenUserId)

        this.socket.emit("refresh.user.info", toUserId, function (result) {
            if (result.code === 200) {
                userInfoCallBack(result.data);
            } else {
                console.error(result.msg)
            }
        });
        const historyMsg = this._getStorageHistoryMsg(toUserId);
        this.listenHistoryMsgCallBack(historyMsg);

        //计算未读消息的ID
        const unReadMsgIds = [];
        historyMsg.forEach((msgInfo, index) => {
            if (msgInfo.isRead === 'N' && msgInfo.from === toUserId) {
                unReadMsgIds.push(msgInfo.id);
                historyMsg[index] = { ...msgInfo, isRead: 'Y' };
            }
        });
        if (unReadMsgIds.length > 0) {
            //更改缓存中的数据
            const historyMsgKey = this._getHistoryMsgCacheKey(toUserId);
            localStorage.setItem(historyMsgKey, JSON.stringify(historyMsg));

            //通知页面更改
            if (this.listenRecentChatsCallBack) {
                this.listenRecentChatsCallBack(this._getRecentChats())
            }

            this.socket.emit("single.read.msg", {
                toUserId: toUserId,
                msgIds: unReadMsgIds
            }, function (state) {
                console.log("single.read.msg", state);
            });
        }
    },

    destroyChat() {
        console.log('结束聊天', this.listenUserId)
        this.listenHistoryMsgCallBack = null;
        this.listenUserId = null;
        this.listenUserInfoCallBack = null;
    },
    //更新用户信息
    updateUserInfo(nickName, avatar) {
        this.socket.emit("update.user.info", {
            nickName, avatar
        }, function (state) {
            console.log("updateUserInfo", state);
        });
    },
    //更新用户信息
    receiveOfflineMsg() {
        this.socket.emit("receive.offline.msg", {}, function (result) {
            console.log("接收离线消息", result);
        });
    },

    //发送文字消息
    sendTxtMsg(toUserId, msgBody) {
        this._sendChatMsg(toUserId, 'TEXT', msgBody);
    },
    //发送图片消息
    sendImageMsg(toUserId, msgBody) {
        this._sendChatMsg(toUserId, 'IMAGE', msgBody);
    },
    listenRecentChats(callBack) {
        this.listenRecentChatsCallBack = callBack;
        this.listenRecentChatsCallBack(this._getRecentChats());
    },
    listenHistoryMsg(callBack) {
        this.listenHistoryMsgCallBack = callBack;
    },
    //获取最近聊天人员对象
    _getRecentChats() {
        const recentChats = [];
        const _this = this;
        for (let i = 0; i < localStorage.length; i++) {
            const key = localStorage.key(i);
            if (key.startsWith("U_TALK_USER_INFO:" + this.accessKeyId + ":")) {
                const userInfo = JSON.parse(localStorage.getItem(key));
                let recentChat = {
                    userId: userInfo.userId,
                    avatar: userInfo.avatar,
                    nickName: userInfo.nickName,
                    lastMsg: null,
                    unReadCount: 0
                }
                const historyMsg = _this._getStorageHistoryMsg(userInfo.userId);

                if (historyMsg) {
                    recentChat.lastMsg = historyMsg[historyMsg.length - 1];
                    let unReadCount = 0;
                    historyMsg.forEach(e => {
                        if (e.isRead === 'N' && e.from === userInfo.userId) {
                            unReadCount++;
                        }
                    });
                    recentChat.unReadCount = unReadCount;
                }
                recentChats.push(recentChat)
            }
        }
        recentChats.sort(function (a, b) {
            console.log(a, b)
            if (a.lastMsg && a.lastMsg.time && b.lastMsg && b.lastMsg.time) {
                return b.lastMsg.time - a.lastMsg.time;
            }
        });
        return recentChats;
    },
    _sendChatMsg(toUserId, msgType, msgBody) {
        const _this = this;
        this.socket.emit("single.chat.msg", {
            toUserId: toUserId,
            msgType: msgType,
            msgBody: msgBody
        }, function (result) {
            //发送结果回调
            if (result.code === 200) {
                const msgInfo = result.data;
                _this._setStorageUserInfo(msgInfo.to);
                _this._setStorageHistoryMsg(msgInfo.to.userId, msgInfo);
            }
        });
    },
    _setMsgReadSate(data) {
        const historyMsg = this._getStorageHistoryMsg(data.fromUserId);
        //计算未读消息的ID
        historyMsg.forEach((msgInfo, index) => {
            if (msgInfo.isRead === 'N' && data.msgIds.includes(msgInfo.id)) {
                historyMsg[index] = { ...msgInfo, isRead: 'Y' };
            }
        });
        //更改缓存中的数据
        const historyMsgKey = this._getHistoryMsgCacheKey(data.fromUserId);
        localStorage.setItem(historyMsgKey, JSON.stringify(historyMsg));

        //通知页面更改
        if (this.listenHistoryMsgCallBack) {
            this.listenHistoryMsgCallBack(historyMsg)
        }
    },
    _setStorageHistoryMsg(userId, msgInfo) {
        const listHistoryMsg = this._getStorageHistoryMsg(userId);
        let isExist = false;

        const tempMsg = {
            id: msgInfo.id,
            from: msgInfo.from.userId,
            msgType: msgInfo.msgType,
            msgBody: msgInfo.msgBody,
            time: msgInfo.time,
            isRead: msgInfo.isRead ?? 'N',
        };

        listHistoryMsg.forEach((info, index) => {
            if (info.id === msgInfo.id) {
                isExist = true;
                listHistoryMsg[index] = tempMsg;
            }
        });

        if (!isExist) {
            listHistoryMsg.push(tempMsg);
        }


        const historyMsgKey = this._getHistoryMsgCacheKey(userId);
        localStorage.setItem(historyMsgKey, JSON.stringify(listHistoryMsg))
        if (this.listenHistoryMsgCallBack) {
            this.listenHistoryMsgCallBack(listHistoryMsg)
        }
        if (this.listenRecentChatsCallBack) {
            this.listenRecentChatsCallBack(this._getRecentChats())
        }
    },
    _getStorageHistoryMsg(userId) {
        const historyMsgKey = this._getHistoryMsgCacheKey(userId);
        const jsonString = localStorage.getItem(historyMsgKey);
        let listHistoryMsg = [];
        if (jsonString) {
            listHistoryMsg = JSON.parse(jsonString);
        }
        return listHistoryMsg;
    },
    _setStorageUserInfo(userInfo) {
        const userInfoKey = this._getUserInfoCacheKey(userInfo.userId);
        localStorage.setItem(userInfoKey, JSON.stringify(userInfo));
        if (this.listenUserId === userInfo.userId) {
            this.listenUserInfoCallBack(userInfo);
        }

        if (this.listenRecentChatsCallBack) {
            this.listenRecentChatsCallBack(this._getRecentChats());
        }
    },
    _getStorageUserInfo(userId) {
        const userInfoKey = this._getUserInfoCacheKey(userId);
        const jsonString = localStorage.getItem(userInfoKey);
        if (jsonString) {
            return JSON.parse(jsonString);
        }
    },
    _getHistoryMsgCacheKey(userId) {
        return "U_TALK_HISTORY_MSG:" + this.accessKeyId + ":" + userId;
    },
    _getUserInfoCacheKey(userId) {
        return "U_TALK_USER_INFO:" + this.accessKeyId + ":" + userId;
    }
}

export default UTalkSDK;